# -*- encoding=utf8 -*-

import os
import urllib.request
import base64
import json

GITHUB_API_URL = "https://api.github.com/"

def ct_getRepoContents(owner, repo, path):
    '''获取Github仓库的目录内容
    '''
    url = GITHUB_API_URL + "repos/%s/%s/contents/%s" % (owner, repo, path)
    headers = { 
        "accept" : "application/vnd.github.v3+json",
        "User-Agent" : "Awesome-Octocat-App",
        "Authorization" : "token f59da977d59da3ef38393c38c9038ba2e5188aeb"
    }
    req = urllib.request.Request(url, headers=headers)
    
    try:
        ret = urllib.request.urlopen(req).read()
        return json.loads(ret)
    except urllib.request.HTTPError as error:
        print("*************** start ***************\r\n请求出错[%d]: %s\r\n%s\r\n*************** end ***************\r\n" % (error.code, error.msg, error.geturl()))
        return None


def ct_getCocoaPodsRepoContents(path):
    '''获取指定目录(路径)下的内容列表
    '''
    if path.startswith("Specs/"):
        return ct_getRepoContents("CocoaPods", "Specs", path)
    else:
        return ct_getRepoContents("CocoaPods", "Specs", os.path.join("Specs", path))


def ct_getCocoaPodsRepoFileContent(path):
    '''获取指定文件的内容
    '''
    ret = ct_getCocoaPodsRepoContents(path)
    if ret and isinstance(ret, dict):
        if ret["type"] == "file":
            if ret["encoding"] == "base64":
                return base64.b64decode(ret["content"]).decode("utf-8")
            else:
                print("不支持的文件编码类型: " + ret["encoding"])